//
//  QueryUsersViewController.m
//  cliqset
//
//  Created by David Hinson on 4/3/09.
//  Copyright 2009 Cliqset, Inc.. All rights reserved.
//

#import "QueryUsersViewController.h"
#import "cliqsetAppDelegate.h"

@implementation QueryUsersViewController

@synthesize queryTable;
@synthesize hoverView;
@synthesize sb;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
	self.title = @"Find Users";
	
    hoverView.center   = [self view].center;
	
	[[self view] addSubview:hoverView];
    [[self view] bringSubviewToFront:hoverView];
	
	[sb becomeFirstResponder];
	
	sb.autocorrectionType     = UITextAutocorrectionTypeNo;
	sb.autocapitalizationType = UITextAutocapitalizationTypeWords;
}

- (void)showHoverView:(BOOL)show
{
	// fade animate the view out of view by affecting its alpha
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:0.40];
    
	if (show)
	{
		hoverView.alpha = 0.85;
	}
	else
	{
		hoverView.alpha = 0.0;
	}
	
	[UIView commitAnimations];
}

#pragma mark ---- searchBar ----

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)passedSearchBar {
    return YES;
}

// Perform query
- (void)searchBarSearchButtonClicked:(UISearchBar *)passedSearchBar {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	[myApp.cliqset query:[passedSearchBar.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];	
	[passedSearchBar resignFirstResponder];
	[myApp showQueryResultsHoverView:YES];
}
	
#pragma mark ---- Table Handling ----

// Number of table sections
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return 1;
}

// Return rows in table
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	return [myApp.queryResults count];
}

// Set row height
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	return 53.0;
}

// Draw cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
    
	UITableViewCell *cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:nil] autorelease];
    [cell backgroundView].opaque=YES;
    [cell backgroundView].clearsContextBeforeDrawing;
	
   	[cell setSelectionStyle:UITableViewCellSelectionStyleGray];	
	cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
	cell.contentView.backgroundColor = [UIColor whiteColor];
	
	UIColor* textColor = [UIColor colorWithRed:62.0/255.0 green:62.0/255.0 blue:62.0/255.0 alpha:1.0];

	Profile * profile = (Profile *)[myApp.queryResults objectAtIndex:indexPath.row];
		
	NSData* imageData         = profile.basicProfile.avatarBlob;
	UIImage * graphic         = (UIImage*)[[UIImage alloc] initWithData:imageData];
	
	UIImageView *showImage    = [[UIImageView alloc] initWithFrame:CGRectMake(10.0, ((54-(40 * graphic.size.height / graphic.size.width))/2.0), 40.0, 40.0 * (graphic.size.height / graphic.size.width))];
    showImage.opaque          = NO;    
	showImage.image           = graphic;
	
	UIView * imageBackground  = [[UIView alloc] init];
	CGRect adjFrame           = showImage.frame;
	adjFrame.origin.x--;
	adjFrame.origin.y--;
	adjFrame.size.height+=2;
	adjFrame.size.width+=2;
	imageBackground.backgroundColor = [UIColor grayColor];
	imageBackground.frame     = adjFrame;
	[cell addSubview:imageBackground];
	[imageBackground release];
	
	// Fonts for Labels
	UIFont* teeny_font      = [UIFont systemFontOfSize:14];
	UIFont* bold_large_font = [UIFont boldSystemFontOfSize:18];
	
	// Allocate labels
	UILabel *nameLabel        = [[UILabel alloc] initWithFrame:CGRectMake(60.0, 7.0, 200.0, 20.0)];
	UILabel *jobLabel         = [[UILabel alloc] initWithFrame:CGRectMake(60.0, 27.0, 200.0, 20.0)];
	
	// Build Name Label
	nameLabel.text			  = [@"" stringByAppendingFormat:@"%@ %@", 
								 profile.basicProfile.givenName == nil? @"" : profile.basicProfile.givenName, 
								 profile.basicProfile.familyName == nil? @"" : profile.basicProfile.familyName];
	nameLabel.font            = bold_large_font;
	
	nameLabel.backgroundColor        = [UIColor clearColor];
	jobLabel.backgroundColor         = [UIColor clearColor];
	
	// Set text color
	nameLabel.textColor       = textColor;
	jobLabel.textColor        = textColor;
	cell.textColor            = textColor;
	
	// Set label in cell
	[cell addSubview:nameLabel];
	
	// Do we have a hometown?
	if (profile.basicProfile.locality) {
		// Build company label
		jobLabel.text		  = profile.basicProfile.locality;
		jobLabel.font         = teeny_font;
		
		// Set label in cell
		[cell addSubview:jobLabel];
	}
	
	// Add image to cell
	[cell addSubview:showImage];

	if (0) {
		UIImage * accept = [UIImage imageNamed:@"accept.png"];
	
		UIButton * acceptButton = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
		acceptButton.frame      = CGRectMake(200, 27, 110, 20);	
		acceptButton.tag        = indexPath.row;	
		acceptButton.font       = [UIFont systemFontOfSize:10];
	
		[acceptButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
	
		[acceptButton setTitle:@"      Add Relationship" forState:UIControlStateNormal];
	
		[acceptButton addTarget:self action:@selector(addRelationship:) forControlEvents:UIControlEventTouchUpInside];
	
		UIImageView * aView = [[UIImageView alloc] initWithFrame:CGRectMake(5, 2, 16, 16)];
	
		aView.image = accept;
	
		[acceptButton addSubview:aView];
		[aView release];
	
		[cell addSubview:acceptButton];
		
		[accept release];
		}
	
	// Cleanup our junk
	[showImage release];
	[graphic release];
	[nameLabel release];
	[jobLabel release];
	
	return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	UITableViewCell *hitCell = [tableView cellForRowAtIndexPath:indexPath];	
    [hitCell setSelected:NO animated:YES];
	
	UIBarButtonItem *backBar = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStyleDone target:nil action:nil];
	self.navigationItem.backBarButtonItem = backBar;	
	[backBar release];
	
	Profile * myProfile = (Profile *)[myApp.queryResults objectAtIndex:indexPath.row];
	
	[self showHoverView:YES];
	myApp.relationshipStatus.status    = nil;
	myApp.relationshipStatus.timeStamp = nil;
	[myApp.cliqset getRelationshipStatus:myProfile.userIdentifier];
	[myApp.cliqset loadRelationshipDrillEvents:myProfile.userIdentifier offset:indexPath.row];
}

-(void)reloadData {
	[self.queryTable reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
}

- (void)dealloc {
	[sb release];
	[hoverView release];
	[queryTable release];
    [super dealloc];
}

@end
